// // 定义分页相关的全局变量
// let currentPage = 1;
// let pageSize = 6;  // 默认每页显示6条
// let totalResources = [];  // 存储所有资源
// let totalPages = 0;  // 总页数
// let currentResourceType = "articles";  // 当前资源类型，默认是 "articles"

// // 页面加载完成后，加载资源
// document.addEventListener("DOMContentLoaded", () => {
//     loadResources(currentResourceType);
//     document.getElementById('category-all').classList.add('active');
// });


// // 加载资源
// function loadResources(type) {
//     // 重置分页相关变量
//     currentPage = 1;
//     totalResources = []; // 清空全局资源数据
//     totalPages = 0;

//     if (type === "articles") {
//         loadArticles();
//         document.getElementById("article-list").style.display = "flex";
//         document.getElementById("video-list").style.display = "none";
//     } else if (type === "videos") {
//         loadVideos();
//         document.getElementById("article-list").style.display = "none";
//         document.getElementById("video-list").style.display = "flex";
//     }
// }

// // 从服务器加载文章
// function loadArticles() {
//     fetch('/api/get-articles', {
//         method: 'GET',
//         headers: { 'Content-Type': 'application/json' }
//     })
//     .then(response => response.json())
//     .then(data => {
//         if (data.status === "success") {
//             totalResources = data.articles || []; // 确保数据结构正确
//             totalPages = Math.ceil(totalResources.length / pageSize); // 更新总页数
//             displayArticles();
//             createPagination();
//         } else {
//             console.error("获取文章失败:", data.message);
//         }
//     })
//     .catch(error => {
//         console.error("请求文章失败:", error);
//     });
// }

// // 从服务器加载视频
// function loadVideos() {
//     fetch('/api/get-videos', {
//         method: 'GET',
//         headers: { 'Content-Type': 'application/json' }
//     })
//     .then(response => response.json())
//     .then(data => {
//         if (data.success) {
//             totalResources = data.videos || []; // 确保数据结构正确
//             totalPages = Math.ceil(totalResources.length / pageSize); // 更新总页数
//             displayVideos();
//             createPagination();
//         } else {
//             console.error("获取视频列表失败:", data.message);
//         }
//     })
//     .catch(error => {
//         console.error("请求视频列表失败:", error);
//     });
// }

// // 切换资源类型
// function switchResourceType() {
//     const resourceType = document.getElementById("resource-type").value;
//     currentResourceType = resourceType; // 更新当前资源类型
//     loadResources(resourceType); // 重新加载选择的资源类型
// }


// // 显示文章列表
// function displayArticles() {
//     const articleList = document.getElementById("article-list");
//     articleList.innerHTML = "";  // 清空文章列表

//     const startIndex = (currentPage - 1) * pageSize;
//     const endIndex = startIndex + pageSize;
//     const currentPageResources = totalResources.slice(startIndex, endIndex);

//     currentPageResources.forEach(article => {
//         const articleCard = document.createElement("div");
//         articleCard.className = "resource-card";
//         articleCard.setAttribute("data-category", article.category.toLowerCase());

//         // 添加点击事件，跳转到 articleDetail.html
//         articleCard.addEventListener("click", () => {
//             redirectToArticleDetail(article.article_id, article.title, article.summary, article.category);
//         });

//         articleCard.innerHTML = `
//             <h3>${article.title}</h3>
//             <p>分类: ${article.category}</p>
//             <p>标签: ${article.tags.join(', ')}</p>
//             <p>简介：${article.summary}</p>
//         `;
//         articleList.appendChild(articleCard);
//     });
// }

// // 创建分页按钮
// function createPagination() {
//     const pagination = document.getElementById("pagination");
//     pagination.innerHTML = "";  // 清空分页按钮

//     // 创建上一页按钮
//     if (currentPage > 1) {
//         const prevButton = document.createElement("button");
//         prevButton.innerText = "上一页";
//         prevButton.onclick = () => changePage(currentPage - 1);
//         pagination.appendChild(prevButton);
//     }

//     // 创建页码按钮
//     for (let i = 1; i <= totalPages; i++) {
//         const pageButton = document.createElement("button");
//         pageButton.innerText = i;
//         pageButton.onclick = () => changePage(i);
//         if (i === currentPage) {
//             pageButton.disabled = true;  // 当前页按钮禁用
//         }
//         pagination.appendChild(pageButton);
//     }

//     // 创建下一页按钮
//     if (currentPage < totalPages) {
//         const nextButton = document.createElement("button");
//         nextButton.innerText = "下一页";
//         nextButton.onclick = () => changePage(currentPage + 1);
//         pagination.appendChild(nextButton);
//     }
// }

// // 切换到指定页
// function changePage(page) {
//     if (page >= 1 && page <= totalPages) {
//         currentPage = page;
//         loadResources(currentResourceType);  // 保证重新加载当前资源类型
//         createPagination();
//     }
// }

// // 改变每页显示的条数
// function changePageSize() {
//     pageSize = parseInt(document.getElementById("page-size").value);
//     currentPage = 1;  // 重新从第一页开始
//     totalPages = Math.ceil(totalResources.length / pageSize);  // 重新计算总页数
//     loadResources(currentResourceType);  // 保证重新加载当前资源类型
//     createPagination();
// }

// // 跳转到文章详情页面
// function redirectToArticleDetail(article_id, title, summary, category) {
//     const articleId = encodeURIComponent(article_id);
//     const articleTitle = encodeURIComponent(title);
//     const articleSummary = encodeURIComponent(summary);
//     const articleCategory = encodeURIComponent(category);

//     // 跳转到 articleDetail.html 并传递查询参数
//     window.location.href = `/html/articleDetail.html?article_id=${articleId}&title=${articleTitle}&summary=${articleSummary}&category=${articleCategory}`;
// }

// // 显示视频
// function displayVideos() {
//     const videoList = document.getElementById("video-list");
//     videoList.innerHTML = "";

//     const startIndex = (currentPage - 1) * pageSize;
//     const endIndex = startIndex + pageSize;
//     const currentPageResources = totalResources.slice(startIndex, endIndex);

//     currentPageResources.forEach(video => {
//         const videoCard = document.createElement("div");
//         videoCard.className = "resource-card";
//         videoCard.setAttribute("data-category", video.category.toLowerCase());
//         videoCard.innerHTML = `
//             <h3>${video.title}</h3>
//             <img src="${video.thumbnail_url}" alt="${video.title} 缩略图" style="width:100%; max-width:200px;">
//             <p>${video.description}</p>
//             <p>分类: ${video.category}</p>
//             <button onclick="redirectToVideoPlayer('${video.url}', '${video.title}', '${video.description}', '${video.category}')">播放视频</button>
//         `;
//         videoList.appendChild(videoCard);
//     });
// }

// // 跳转到视频播放器页面
// function redirectToVideoPlayer(url, title, description, category) {
//     const videoUrl = encodeURIComponent(url);
//     const videoTitle = encodeURIComponent(title);
//     const videoDescription = encodeURIComponent(description);
//     const videoCategory = encodeURIComponent(category);

//     // 跳转到 videoPlayer.html 并传递查询参数
//     window.location.href = `/html/videoPlayer.html?url=${videoUrl}&title=${videoTitle}&description=${videoDescription}&category=${videoCategory}`;
// }

// // 根据关键词搜索资源
function searchResources() {
    const keyword = document.getElementById("search-input").value.toLowerCase();
    const resourceType = document.getElementById("resource-type").value;
    const listId = resourceType === "articles" ? "article-list" : "video-list";
    const resourceCards = document.querySelectorAll(`#${listId} .resource-card`);

    resourceCards.forEach(card => {
        card.style.display = card.innerText.toLowerCase().includes(keyword) ? "block" : "none";
    });
}

// // 根据选定的分类筛选资源
// function filterByCategory(category) {
//     // const category = document.getElementById("category").value.toLowerCase();
//     const resourceType = document.getElementById("resource-type").value;
//     const listId = resourceType === "articles" ? "article-list" : "video-list";
//     const resourceCards = document.querySelectorAll(`#${listId} .resource-card`);

//     resourceCards.forEach(card => {
//         const cardCategory = card.getAttribute("data-category")?.toLowerCase() || '';
//         card.style.display = (category === "all" || cardCategory === category) ? "block" : "none";
//     });

//     // 移除之前选中按钮的active类
//     document.querySelectorAll('.category-button.active').forEach(button => {
//         button.classList.remove('active');
//     });
//     // 给当前点击的按钮添加active类，改变字体颜色
//     document.getElementById(`category-${category}`).classList.add('active');
// }
// 定义分页相关的全局变量
let currentPage = 1;
let pageSize = 6;  // 默认每页显示6条
let totalResources = [];  // 存储所有资源
let totalPages = 0;  // 总页数
let currentResourceType = "articles";  // 当前资源类型，默认是 "articles"

// 页面加载完成后，加载资源
document.addEventListener("DOMContentLoaded", () => {
    loadResources(currentResourceType);
    document.getElementById('category-all').classList.add('active');
});

// 加载资源
function loadResources(type) {
    // 重置分页相关变量
    currentPage = 1;
    totalResources = []; // 清空全局资源数据
    totalPages = 0;
    document.getElementById("pagination").innerHTML = ''; // 清空分页

    if (type === "articles") {
        loadArticles();
        document.getElementById("article-list").style.display = "flex";
        document.getElementById("video-list").style.display = "none";
    } else if (type === "videos") {
        loadVideos();
        document.getElementById("article-list").style.display = "none";
        document.getElementById("video-list").style.display = "flex";
    }
}

// 从服务器加载文章
function loadArticles() {
    fetch('/api/get-articles', {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === "success") {
            totalResources = data.articles || []; // 确保数据结构正确
            totalPages = Math.ceil(totalResources.length / pageSize); // 更新总页数
            displayArticles();
            createPagination();
        } else {
            console.error("获取文章失败:", data.message);
        }
    })
    .catch(error => {
        console.error("请求文章失败:", error);
    });
}

// 从服务器加载视频
function loadVideos() {
    fetch('/api/get-videos', {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            totalResources = data.videos || []; // 确保数据结构正确
            totalPages = Math.ceil(totalResources.length / pageSize); // 更新总页数
            displayVideos();
            createPagination();
        } else {
            console.error("获取视频列表失败:", data.message);
        }
    })
    .catch(error => {
        console.error("请求视频列表失败:", error);
    });
}

// 切换资源类型
function switchResourceType() {
    const resourceType = document.getElementById("resource-type").value;
    currentResourceType = resourceType; // 更新当前资源类型
    loadResources(resourceType); // 重新加载选择的资源类型
}

// 显示文章列表
function displayArticles() {
    const articleList = document.getElementById("article-list");
    articleList.innerHTML = "";  // 清空文章列表

    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const currentPageResources = totalResources.slice(startIndex, endIndex);

    currentPageResources.forEach(article => {
        const articleCard = document.createElement("div");
        articleCard.className = "resource-card";
        articleCard.setAttribute("data-category", article.category.toLowerCase());

        articleCard.addEventListener("click", () => {
            redirectToArticleDetail(article.article_id, article.title, article.summary, article.category);
        });

        articleCard.innerHTML = `
            <h3>${article.title}</h3>
            <p>分类: ${article.category}</p>
            <p>标签: ${article.tags.join(', ')}</p>
            <p>简介：${article.summary}</p>
        `;
        articleList.appendChild(articleCard);
    });
}

// 创建分页按钮
function createPagination() {
    const pagination = document.getElementById("pagination");
    pagination.innerHTML = "";  // 清空分页按钮

    if (totalPages <= 1) return; // 如果总页数为 1，直接返回，不创建分页

    // 创建上一页按钮
    if (currentPage > 1) {
        const prevButton = document.createElement("button");
        prevButton.innerText = "上一页";
        prevButton.onclick = () => changePage(currentPage - 1);
        pagination.appendChild(prevButton);
    }

    // 创建页码按钮
    for (let i = 1; i <= totalPages; i++) {
        const pageButton = document.createElement("button");
        pageButton.innerText = i;
        pageButton.onclick = () => changePage(i);
        if (i === currentPage) {
            pageButton.disabled = true;
        }
        pagination.appendChild(pageButton);
    }

    // 创建下一页按钮
    if (currentPage < totalPages) {
        const nextButton = document.createElement("button");
        nextButton.innerText = "下一页";
        nextButton.onclick = () => changePage(currentPage + 1);
        pagination.appendChild(nextButton);
    }
}

// 切换到指定页
function changePage(page) {
    if (page >= 1 && page <= totalPages) {
        currentPage = page;
        loadResources(currentResourceType);
    }
}

// 改变每页显示的条数
function changePageSize() {
    pageSize = parseInt(document.getElementById("page-size").value);
    currentPage = 1;  // 重新从第一页开始
    loadResources(currentResourceType);  // 保证重新加载当前资源类型
}

// 跳转到文章详情页面
function redirectToArticleDetail(article_id, title, summary, category) {
    const articleId = encodeURIComponent(article_id);
    const articleTitle = encodeURIComponent(title);
    const articleSummary = encodeURIComponent(summary);
    const articleCategory = encodeURIComponent(category);

    window.location.href = `/html/articleDetail.html?article_id=${articleId}&title=${articleTitle}&summary=${articleSummary}&category=${articleCategory}`;
}

// 显示视频
function displayVideos() {
    const videoList = document.getElementById("video-list");
    videoList.innerHTML = "";

    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const currentPageResources = totalResources.slice(startIndex, endIndex);

    currentPageResources.forEach(video => {
        const videoCard = document.createElement("div");
        videoCard.className = "resource-card";
        videoCard.setAttribute("data-category", video.category.toLowerCase());
        videoCard.innerHTML = `
            <h3>${video.title}</h3>
            <img src="${video.thumbnail_url}" alt="${video.title} 缩略图" style="width:100%; max-width:200px;">
            <p>${video.description}</p>
            <p>分类: ${video.category}</p>
            <button onclick="redirectToVideoPlayer('${video.url}', '${video.title}', '${video.description}', '${video.category}')">播放视频</button>
        `;
        videoList.appendChild(videoCard);
    });
}

// 跳转到视频详情页面
function redirectToVideoPlayer(url, title, description, category) {
    const videoUrl = encodeURIComponent(url);
    const videoTitle = encodeURIComponent(title);
    const videoDescription = encodeURIComponent(description);
    const videoCategory = encodeURIComponent(category);

    // 跳转到 videoPlayer.html 并传递查询参数
    window.location.href = `/html/videoPlayer.html?url=${videoUrl}&title=${videoTitle}&description=${videoDescription}&category=${videoCategory}`;
}

// 切换分类时调用的函数
function filterByCategory(category) {
    // 移除所有按钮的 active 类
    const buttons = document.querySelectorAll('.category-button');
    buttons.forEach(button => {
        button.classList.remove('active');
    });

    // 给点击的按钮添加 active 类
    const selectedButton = document.getElementById('category-' + category);
    selectedButton.classList.add('active');

    // 过滤资源（这里只是展示的效果，具体筛选逻辑可以根据需求进行调整）
    const cards = document.querySelectorAll(".resource-card");
    cards.forEach(card => {
        const cardCategory = card.getAttribute("data-category").toLowerCase();
        if (category === "all" || cardCategory === category.toLowerCase()) {
            card.style.display = "block";
        } else {
            card.style.display = "none";
        }
    });
}
